using System.Text.Json.Serialization;

namespace KrasDD.Dtos
{
    /// <summary>
    /// API统一响应格式
    /// </summary>
    /// <typeparam name="T">响应数据类型</typeparam>
    public class ApiResponse<T>
    {
        /// <summary>
        /// 状态码
        /// </summary>
        public int Code { get; set; } = 200;
        
        /// <summary>
        /// 是否成功
        /// </summary>
        public bool Success { get; set; } = true;
        
        /// <summary>
        /// 响应数据
        /// </summary>
        public T? Data { get; set; }
        
        /// <summary>
        /// 错误信息
        /// </summary>
        public string? Error { get; set; }
        
        /// <summary>
        /// 异常堆栈信息
        /// </summary>
        public string? Stack { get; set; }
        
        /// <summary>
        /// 成功响应
        /// </summary>
        /// <param name="data">响应数据</param>
        /// <returns>API响应</returns>
        public static ApiResponse<T> Ok(T data)
        {
            return new ApiResponse<T>
            {
                Code = 200,
                Success = true,
                Data = data,
                Error = null
            };
        }
        
        /// <summary>
        /// 失败响应
        /// </summary>
        /// <param name="error">错误信息</param>
        /// <param name="code">状态码</param>
        /// <returns>API响应</returns>
        public static ApiResponse<T> Fail(string error, int code = 400)
        {
            return new ApiResponse<T>
            {
                Code = code,
                Success = false,
                Data = default,
                Error = error
            };
        }
        
        /// <summary>
        /// 异常响应
        /// </summary>
        /// <param name="error">错误信息</param>
        /// <param name="stack">异常堆栈信息</param>
        /// <param name="code">状态码</param>
        /// <returns>API响应</returns>
        public static ApiResponse<T> Exception(string error, string stack, int code = 500)
        {
            return new ApiResponse<T>
            {
                Code = code,
                Success = false,
                Data = default,
                Error = error,
                Stack = stack
            };
        }
    }
}